package com.unitechs.trap.excel.webapi.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j
public class JsonUtil {

    /**
     * 从给定的XML字符串中提取陷阱数据，并将其转换为JSON对象。
     *
     * @param xml 包含陷阱数据的XML字符串
     * @return 陷阱数据的JSON对象，如果无法提取数据，则返回null
     */
    public static JSONObject getTrapJson(String xml) {
        log.info("xml{}",xml);
        String protocol = "";
        if (xml.toLowerCase().contains("vbs")) {
            protocol = "VBS";
        } else if (xml.toLowerCase().contains("udp")) {
            protocol = "UDP";
        }
        Pattern pattern;
        Matcher matcher;
        JSONObject json = new JSONObject();
        switch (protocol) {
            case "VBS":
                pattern = Pattern.compile("VBS\\[([\\s\\S]*)]");
                matcher = pattern.matcher(xml);

                if (matcher.find()) {
                    String vbsData = matcher.group(1);
                    String[] vbsElements = vbsData.split("; ");


                    for (String element : vbsElements) {
                        String[] keyValue = element.split(" = ");
                        if (keyValue.length >= 2) {
                            json.put(keyValue[0], keyValue[1]);
                        } else {
                            json.put(keyValue[0], "");
                        }
                    }
                }
                return json;
            case "UDP":
                log.info("截取前xml{}",xml);
                xml=xml.replaceAll("\\b\\w+:","");
                xml=xml.replace("\"","");
                log.info("截取后xml{}",xml);
                pattern = Pattern.compile("(?<key>\\S+)\\s*=\\s*(?<value>\\S*)");
                matcher = pattern.matcher(xml);
                while (matcher.find()) {
                    // Extract the SNMP variable and its value from the match
                    String key = matcher.group("key");
                    String value = matcher.group("value");
                    log.info("key{}",key);
                    log.info("value{}",value);
                    // Add the SNMP variable and its value to the map
                    json.put(key, value);
                }
                return json;
            default:
                return null;
        }

    }



}
